package com.runda.service.impl;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.bbjob.mapper.ExamInfoMapper;
import com.bbjob.mapper.QueChoiceAnalysisMapper;
import com.bbjob.mapper.QueChoiceBankMapper;
import com.bbjob.mapper.QueChoiceMapper;
import com.bbjob.mapper.QueChoiceitemMapper;
import com.bbjob.mapper.QueOperationAnalysisMapper;
import com.bbjob.mapper.QueOperationBankMapper;
import com.bbjob.mapper.QueOperationItemMapper;
import com.bbjob.mapper.QueOperationMapper;
import com.bbjob.mapper.QuestionBankMapper;
import com.bbjob.mapper.SysOrganizationMapper;
import com.bbjob.mapper.UserMapper;
import com.bbjob.model.ExamInfo;
import com.bbjob.model.QueChoice;
import com.bbjob.model.QueChoiceAnalysis;
import com.bbjob.model.QueChoiceBank;
import com.bbjob.model.QueChoiceWithBank;
import com.bbjob.model.QueChoiceitem;
import com.bbjob.model.QueOperation;
import com.bbjob.model.QueOperationAnalysis;
import com.bbjob.model.QueOperationBank;
import com.bbjob.model.QueOperationItem;
import com.bbjob.model.QueOperationWithBank;
import com.bbjob.model.QuestionBank;
import com.bbjob.model.SysDictionary;
import com.bbjob.model.SysOrganization;
import com.bbjob.model.User;
import com.bbjob.util.Tool;
import com.bbjob.util.service.impl.BaseService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.runda.service.IQuestionBankService;
import com.runda.system.service.DicService;

import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

@Service
public class QuestionBankServiceImpl extends BaseService<QuestionBank> implements IQuestionBankService {

	@Resource
	private ExamInfoMapper examInfoMapper;
	@Resource
	private QuestionBankMapper questionBankMapper;
	@Resource
	private UserMapper usermapper;
	@Resource
	private SysOrganizationMapper organmapper;
	@Resource
	private QueChoiceMapper choicemapper;
	@Autowired
	private QueChoiceitemMapper choiceitemmapper;
	@Autowired
	private QueChoiceBankMapper choicebankmapper;
	@Resource
	private QueOperationMapper operationmapper;
	@Autowired
	private QueOperationItemMapper operationitemmapper;
	@Autowired
	private QueOperationBankMapper operationbankmapper;
	@Autowired
	private QueChoiceAnalysisMapper quechoiceAnalysisMapper;
	@Autowired
	private QueOperationAnalysisMapper queOperationAnalysisMapper;
	@Autowired
	private DicService dicservice;

	@Override
	public List<QuestionBank> selectByExamId(Integer id) {

		ExamInfo examInfo = examInfoMapper.selectByPrimaryKey(id);

		if (examInfo != null) {
			String queIds = examInfo.getqId();

			if (queIds != null && !"".equals(queIds)) {
				String[] ids = queIds.split(",");

				Example example = new Example(QuestionBank.class);
				example.createCriteria().andIn("id", Arrays.asList(ids));

				return questionBankMapper.selectByExample(example);
			}
		}

		return null;
	}

	@Override
	public PageInfo<QuestionBank> getBank(Integer type, String name, Integer difficulty, Integer userid, Integer page,
			Integer size) {
		User user = usermapper.selectByPrimaryKey(userid);
		// 首先查看organcode是否有效
		/*
		 * if(organ != null && StringUtil.isNotEmpty(organ.getUniqueCode())) { String
		 * organcode = organ.getUniqueCode(); Example example = new
		 * Example(SysOrganization.class); Example.Criteria criteria =
		 * example.createCriteria(); criteria.andEqualTo("uniqueCode", organcode);
		 * List<SysOrganization> result = organmapper.selectByExample(example); if
		 * (result == null || result.size() == 0) { // 没有对应的组织 return null; } //
		 * 如果有的话，查看id是否对应 if (!user.getOrganId().equals(result.get(0).getId())) { //
		 * 用户的组织和传来的组织对不上 return null; } }
		 */
		if (user == null) {
			return null;
		}
		List<User> userlist = usermapper.selectAll();
		List<SysOrganization> organlst = organmapper.selectAll();
		List<SysDictionary> diclist = dicservice.getDifficulty();
		Map<Integer, String> map = new HashMap<>();
		Map<String, String> map2 = new HashMap<>();
		Map<Integer, String> map3 = new HashMap<>();
		for (SysOrganization sysOrganization : organlst) {
			if (sysOrganization.getLevel() == 1 && StringUtil.isNotEmpty(sysOrganization.getUniqueCode())
					&& sysOrganization.getPid() == null) {
				map2.put(sysOrganization.getUniqueCode(), sysOrganization.getName());
			}
		}
		for (User user2 : userlist) {
			map.put(user2.getId(), user2.getRealname());
		}
		for (SysDictionary sysDictionary : diclist) {
			map3.put(sysDictionary.getId(), sysDictionary.getDicValue());
		}
		if (user.getType() == 2) {
			// 普通老师
			/**
			 * 以下是正常情况
			 */
			PageHelper.startPage(page, size);
			Example ex = new Example(QuestionBank.class);
			Example.Criteria c = ex.createCriteria();
			c.andEqualTo("createrId", userid);
			if (StringUtil.isNotEmpty(name)) {
				c.andLike("title", "%" + name + "%");
			}
			if (type != null) {
				c.andEqualTo("free4", type);
			}
			if (difficulty != null) {
				c.andEqualTo("difficultyId", difficulty);
			}
			c.andEqualTo("isDelete", 0);
			c.andEqualTo("status", 0);
			ex.setOrderByClause(" create_time desc");
			List<QuestionBank> resultList = questionBankMapper.selectByExample(ex);
			for (QuestionBank questionBank : resultList) {
				questionBank.setRealname(map.get(questionBank.getCreaterId()));
				// 填充学校名称
				questionBank.setFree5(map2.get(questionBank.getOrganCode()));
				// 填充难度
				questionBank.setDifficultyName(map3.get(questionBank.getDifficultyId()));
			}
			return new PageInfo<QuestionBank>(resultList);
		} else if (user.getType() == 1) {
			SysOrganization organ = organmapper.selectByPrimaryKey(user.getOrganId());
			// 教务主任

			/**
			 * 以下是正常情况，查看所属学校代码的题库
			 */
			PageHelper.startPage(page, size);
			Example ex = new Example(QuestionBank.class);
			Example.Criteria c = ex.createCriteria();
			c.andEqualTo("organCode", organ.getUniqueCode());
			if (StringUtil.isNotEmpty(name)) {
				c.andLike("title", "%" + name + "%");
			}
			if (type != null) {
				c.andEqualTo("free4", type);
			}
			if (difficulty != null) {
				c.andEqualTo("difficultyId", difficulty);
			}
			c.andEqualTo("isDelete", 0);
			c.andEqualTo("status", 0);
			ex.setOrderByClause(" create_time desc");
			List<QuestionBank> resultList = questionBankMapper.selectByExample(ex);
			for (QuestionBank questionBank : resultList) {
				questionBank.setRealname(map.get(questionBank.getCreaterId()));
				// 填充学校名称
				questionBank.setFree5(map2.get(questionBank.getOrganCode()));
				// 填充难度
				questionBank.setDifficultyName(map3.get(questionBank.getDifficultyId()));
			}
			return new PageInfo<QuestionBank>(resultList);
		} else if (user.getType() == -1) {
			// 超管
			/**
			 * 以下是正常情况，查看所属学校代码的题库
			 */
			PageHelper.startPage(page, size);
			Example ex = new Example(QuestionBank.class);
			Example.Criteria c = ex.createCriteria();
			if (StringUtil.isNotEmpty(name)) {
				c.andLike("title", "%" + name + "%");
			}
			if (type != null) {
				c.andEqualTo("free4", type);
			}
			if (difficulty != null) {
				c.andEqualTo("difficultyId", difficulty);
			}
			c.andEqualTo("isDelete", 0);
			c.andEqualTo("status", 0);
			ex.setOrderByClause(" create_time desc");
			List<QuestionBank> resultList = questionBankMapper.selectByExample(ex);
			for (QuestionBank questionBank : resultList) {
				questionBank.setRealname(map.get(questionBank.getCreaterId()));
				// 填充学校名称
				questionBank.setFree5(map2.get(questionBank.getOrganCode()));
				// 填充难度
				questionBank.setDifficultyName(map3.get(questionBank.getDifficultyId()));
			}
			return new PageInfo<QuestionBank>(resultList);
		} else {
			// 什么也不是
			return null;
		}

	}

	@Override
	public PageInfo<QuestionBank> getFreeBank(Integer type, String name, Integer difficulty, Integer page,
			Integer size) {
		// User user = usermapper.selectByPrimaryKey(userid);
		/*
		 * SysOrganization organ = organmapper.selectByPrimaryKey(user.getOrganId());
		 * String organcode = organ.getUniqueCode();
		 * if(StringUtil.isNotEmpty(organcode)) { // 首先查看organcode是否有效 Example example =
		 * new Example(SysOrganization.class); Example.Criteria criteria =
		 * example.createCriteria(); criteria.andEqualTo("uniqueCode", organcode);
		 * List<SysOrganization> result = organmapper.selectByExample(example); if
		 * (result == null || result.size() == 0) { // 没有对应的组织 return null; } //
		 * 如果有的话，查看id是否对应 if (!user.getOrganId().equals(result.get(0).getId())) { //
		 * 用户的组织和传来的组织对不上 return null; } }
		 */
		/**
		 * 以下是正常情况，查看所属学校代码的题库
		 */
		PageHelper.startPage(page, size);
		Example ex = new Example(QuestionBank.class);
		Example.Criteria c = ex.createCriteria();
		c.andEqualTo("status", 1);
		if (StringUtil.isNotEmpty(name)) {
			c.andLike("title", "%" + name + "%");
		}
		if (type != null) {
			c.andEqualTo("free4", type);
		}
		if (difficulty != null) {
			c.andEqualTo("difficultyId", difficulty);
		}
		c.andEqualTo("isDelete", 0);
		c.andEqualTo("status", 1);
		ex.setOrderByClause(" create_time desc");
		List<QuestionBank> resultList = questionBankMapper.selectByExample(ex);
		List<User> userlist = usermapper.selectAll();
		List<SysOrganization> organlst = organmapper.selectAll();
		List<SysDictionary> diclist = dicservice.getDifficulty();
		Map<Integer, String> map3 = new HashMap<>();
		Map<Integer, String> map = new HashMap<>();
		Map<String, String> map2 = new HashMap<>();
		for (SysOrganization sysOrganization : organlst) {
			if (sysOrganization.getLevel() == 1 && StringUtil.isNotEmpty(sysOrganization.getUniqueCode())
					&& sysOrganization.getPid() == null) {
				map2.put(sysOrganization.getUniqueCode(), sysOrganization.getName());
			}
		}
		for (User user2 : userlist) {
			map.put(user2.getId(), user2.getRealname());
		}
		for (SysDictionary sysDictionary : diclist) {
			map3.put(sysDictionary.getId(), sysDictionary.getDicValue());
		}
		for (QuestionBank questionBank : resultList) {
			questionBank.setRealname(map.get(questionBank.getCreaterId()));
			// 填充学校
			questionBank.setFree5(map2.get(questionBank.getOrganCode()));
			// 填充难度
			questionBank.setDifficultyName(map3.get(questionBank.getDifficultyId()));
		}
		return new PageInfo<QuestionBank>(resultList);
	}

	@Override
	public Map<String, Object> getChoice(String bankid, String tag, String name, Integer type, Integer userid,
			Integer page, Integer size, Integer bankType) {
		User user = usermapper.selectByPrimaryKey(userid);
		/*
		 * SysOrganization organ = organmapper.selectByPrimaryKey(user.getOrganId());
		 * String organcode = organ.getUniqueCode();
		 * if(StringUtil.isNotEmpty(organcode)) { // 首先查看organcode是否有效 Example example =
		 * new Example(SysOrganization.class); Example.Criteria criteria =
		 * example.createCriteria(); criteria.andEqualTo("uniqueCode", organcode);
		 * List<SysOrganization> result = organmapper.selectByExample(example); if
		 * (result == null || result.size() == 0) { // 没有对应的组织 return null; } //
		 * 如果有的话，查看id是否对应 if (!user.getOrganId().equals(result.get(0).getId())) { //
		 * 用户的组织和传来的组织对不上 return null; } }
		 */
		List<String> list = new ArrayList<String>();
		if (StringUtil.isNotEmpty(tag)) {
			String[] tags = tag.split(",");
			for (String string : tags) {
				list.add(string);
			}
		}
		/**
		 * 以下是正常情况，查看所属学校代码的题库
		 */
		if (user.getType() == 1) {
			// 教导主任
			SysOrganization organ = organmapper.selectByPrimaryKey(user.getOrganId());
			List<QueChoiceWithBank> choicelist = choicemapper.selectQueChoiceWithBank(list, bankid, name, null,
					organ.getUniqueCode(), type, 0, page, size, bankType);
			List<User> userlist = usermapper.selectAll();
			List<SysOrganization> organlst = organmapper.selectAll();
			Map<Integer, String> map = new HashMap<>();
			Map<String, String> map2 = new HashMap<>();
			for (SysOrganization sysOrganization : organlst) {
				if (sysOrganization.getLevel() == 1 && StringUtil.isNotEmpty(sysOrganization.getUniqueCode())
						&& sysOrganization.getPid() == null) {
					map2.put(sysOrganization.getUniqueCode(), sysOrganization.getName());
				}
			}
			for (User user2 : userlist) {
				map.put(user2.getId(), user2.getRealname());
			}
			for (QueChoiceWithBank queChoiceWithBank : choicelist) {
				queChoiceWithBank.setFree3(map.get(queChoiceWithBank.getCreaterId()));
				queChoiceWithBank.setFree5(map2.get(queChoiceWithBank.getOrganCode()));
			}
			Map<String, Object> result = new HashMap<>();
			result.put("total", choicemapper.selectQueChoiceWithBank(list, bankid, name, null, organ.getUniqueCode(),
					type, 0, null, null, bankType).size());
			result.put("pageNum", page);
			result.put("pageSize", size);
			result.put("list", choicelist);
			return result;

		} else if (user.getType() == 2) {
			// 普通教师
			List<QueChoiceWithBank> choicelist = choicemapper.selectQueChoiceWithBank(list, bankid, name, userid, null,
					type, 0, page, size, bankType);
			List<User> userlist = usermapper.selectAll();
			List<SysOrganization> organlst = organmapper.selectAll();
			Map<Integer, String> map = new HashMap<>();
			Map<String, String> map2 = new HashMap<>();
			for (SysOrganization sysOrganization : organlst) {
				if (sysOrganization.getLevel() == 1 && StringUtil.isNotEmpty(sysOrganization.getUniqueCode())
						&& sysOrganization.getPid() == null) {
					map2.put(sysOrganization.getUniqueCode(), sysOrganization.getName());
				}
			}
			for (User user2 : userlist) {
				map.put(user2.getId(), user2.getRealname());
			}
			for (QueChoiceWithBank queChoiceWithBank : choicelist) {
				queChoiceWithBank.setFree3(map.get(queChoiceWithBank.getCreaterId()));
				queChoiceWithBank.setFree5(map2.get(queChoiceWithBank.getOrganCode()));
			}

			Map<String, Object> result = new HashMap<>();
			result.put("total", choicemapper
					.selectQueChoiceWithBank(list, bankid, name, userid, null, type, 0, null, null, bankType).size());
			result.put("pageNum", page);
			result.put("pageSize", size);
			result.put("list", choicelist);
			return result;
		} else if (user.getType() == -1) {
			// 超管
			List<QueChoiceWithBank> choicelist = choicemapper.selectQueChoiceWithBank(list, bankid, name, null, null,
					type, 0, page, size, bankType);
			List<User> userlist = usermapper.selectAll();
			List<SysOrganization> organlst = organmapper.selectAll();
			Map<Integer, String> map = new HashMap<>();
			Map<String, String> map2 = new HashMap<>();
			for (SysOrganization sysOrganization : organlst) {
				if (sysOrganization.getLevel() == 1 && StringUtil.isNotEmpty(sysOrganization.getUniqueCode())
						&& sysOrganization.getPid() == null) {
					map2.put(sysOrganization.getUniqueCode(), sysOrganization.getName());
				}
			}
			for (User user2 : userlist) {
				map.put(user2.getId(), user2.getRealname());
			}
			for (QueChoiceWithBank queChoiceWithBank : choicelist) {
				queChoiceWithBank.setFree3(map.get(queChoiceWithBank.getCreaterId()));
				queChoiceWithBank.setFree5(map2.get(queChoiceWithBank.getOrganCode()));
			}
			Map<String, Object> result = new HashMap<>();
			result.put("total", choicemapper
					.selectQueChoiceWithBank(list, bankid, name, null, null, type, 0, null, null, bankType).size());
			result.put("pageNum", page);
			result.put("pageSize", size);
			result.put("list", choicelist);
			return result;
		} else {
			return null;
		}

	}

	@Override
	public Map<String, Object> getFreeChoice(String bankid, String tag, String name, Integer type, Integer userid,
			Integer page, Integer size,Integer bankType) {
		/*
		 * User user = usermapper.selectByPrimaryKey(userid); SysOrganization organ =
		 * organmapper.selectByPrimaryKey(user.getOrganId()); String organcode =
		 * organ.getUniqueCode(); if(StringUtil.isNotEmpty(organcode)) { //
		 * 首先查看organcode是否有效 Example example = new Example(SysOrganization.class);
		 * Example.Criteria criteria = example.createCriteria();
		 * criteria.andEqualTo("uniqueCode", organcode); List<SysOrganization> result =
		 * organmapper.selectByExample(example); if (result == null || result.size() ==
		 * 0) { // 没有对应的组织 return null; } // 如果有的话，查看id是否对应 if
		 * (!user.getOrganId().equals(result.get(0).getId())) { // 用户的组织和传来的组织对不上 return
		 * null; } }
		 */
		/**
		 * 以下是正常情况
		 */
		List<String> list = new ArrayList<String>();
		if (StringUtil.isNotEmpty(tag)) {
			String[] tags = tag.split(",");
			for (String string : tags) {
				list.add(string);
			}
		}
		List<QueChoiceWithBank> choicelist = choicemapper.selectQueChoiceWithBank(list, bankid, name, null, null, type,
				1, page, size, bankType);
		List<User> userlist = usermapper.selectAll();
		List<SysOrganization> organlst = organmapper.selectAll();
		Map<Integer, String> map = new HashMap<>();
		Map<String, String> map2 = new HashMap<>();
		for (SysOrganization sysOrganization : organlst) {
			if (sysOrganization.getLevel() == 1 && StringUtil.isNotEmpty(sysOrganization.getUniqueCode())
					&& sysOrganization.getPid() == null) {
				map2.put(sysOrganization.getUniqueCode(), sysOrganization.getName());
			}
		}
		for (User user2 : userlist) {
			map.put(user2.getId(), user2.getRealname());
		}
		for (QueChoiceWithBank queChoiceWithBank : choicelist) {
			queChoiceWithBank.setFree3(map.get(queChoiceWithBank.getCreaterId()));
			queChoiceWithBank.setFree5(map2.get(queChoiceWithBank.getOrganCode()));
		}
		Map<String, Object> result = new HashMap<>();
		result.put("total", choicemapper
				.selectQueChoiceWithBank(list, bankid, name, null, null, type, 1, null, null, bankType).size());
		result.put("pageNum", page);
		result.put("pageSize", size);
		result.put("list", choicelist);
		return result;
	}

	@Override
	public Map<String, Object> getOperation(String tag, String bankid, String name, Integer type, Integer userid,
			Integer page, Integer size) {
		User user = usermapper.selectByPrimaryKey(userid);
		/*
		 * SysOrganization organ = organmapper.selectByPrimaryKey(user.getOrganId());
		 * String organcode = organ.getUniqueCode();
		 * if(StringUtil.isNotEmpty(organcode)) { // 首先查看organcode是否有效 Example example =
		 * new Example(SysOrganization.class); Example.Criteria criteria =
		 * example.createCriteria(); criteria.andEqualTo("uniqueCode", organcode);
		 * List<SysOrganization> result = organmapper.selectByExample(example); if
		 * (result == null || result.size() == 0) { // 没有对应的组织 return null; } //
		 * 如果有的话，查看id是否对应 if (!user.getOrganId().equals(result.get(0).getId())) { //
		 * 用户的组织和传来的组织对不上 return null; } }
		 */
		/**
		 * 以下是正常情况，查看所属学校代码的题库
		 */
		List<String> list = new ArrayList<String>();
		if (StringUtil.isNotEmpty(tag)) {
			String[] tags = tag.split(",");
			for (String string : tags) {
				list.add(string);
			}
		}
		if (user.getType() == 1) {
			// 教导主任
			SysOrganization organ = organmapper.selectByPrimaryKey(user.getOrganId());
			List<QueOperationWithBank> operationlist = operationmapper.selectQueOperationWithBank(list, bankid, name,
					null, organ.getUniqueCode(), type, 0, page, size);
			List<User> userlist = usermapper.selectAll();
			List<SysOrganization> organlst = organmapper.selectAll();
			Map<Integer, String> map = new HashMap<>();
			Map<String, String> map2 = new HashMap<>();
			for (SysOrganization sysOrganization : organlst) {
				if (sysOrganization.getLevel() == 1 && StringUtil.isNotEmpty(sysOrganization.getUniqueCode())
						&& sysOrganization.getPid() == null) {
					map2.put(sysOrganization.getUniqueCode(), sysOrganization.getName());
				}
			}
			for (User user2 : userlist) {
				map.put(user2.getId(), user2.getRealname());
			}
			for (QueOperationWithBank queOperationWithBank : operationlist) {
				queOperationWithBank.setFree3(map.get(queOperationWithBank.getCreaterId()));
				queOperationWithBank.setFree5(map2.get(queOperationWithBank.getOrganCode()));
			}
			Map<String, Object> result = new HashMap<>();
			result.put("total", operationmapper
					.selectQueOperationWithBank(list, bankid, name, null, organ.getUniqueCode(), type, 0, null, null)
					.size());
			result.put("pageNum", page);
			result.put("pageSize", size);
			result.put("list", operationlist);

			return result;
		} else if (user.getType() == 2) {
			// 普通教师
			List<QueOperationWithBank> operationlist = operationmapper.selectQueOperationWithBank(list, bankid, name,
					userid, null, type, 0, page, size);
			List<User> userlist = usermapper.selectAll();
			List<SysOrganization> organlst = organmapper.selectAll();
			Map<Integer, String> map = new HashMap<>();
			Map<String, String> map2 = new HashMap<>();
			for (SysOrganization sysOrganization : organlst) {
				if (sysOrganization.getLevel() == 1 && StringUtil.isNotEmpty(sysOrganization.getUniqueCode())
						&& sysOrganization.getPid() == null) {
					map2.put(sysOrganization.getUniqueCode(), sysOrganization.getName());
				}
			}
			for (User user2 : userlist) {
				map.put(user2.getId(), user2.getRealname());
			}
			for (QueOperationWithBank queOperationWithBank : operationlist) {
				queOperationWithBank.setFree3(map.get(queOperationWithBank.getCreaterId()));
				queOperationWithBank.setFree5(map2.get(queOperationWithBank.getOrganCode()));
			}
			Map<String, Object> result = new HashMap<>();
			result.put("total", operationmapper
					.selectQueOperationWithBank(list, bankid, name, userid, null, type, 0, null, null).size());
			result.put("pageNum", page);
			result.put("pageSize", size);
			result.put("list", operationlist);

			return result;
		} else if (user.getType() == -1) {
			// 超管
			List<QueOperationWithBank> operationlist = operationmapper.selectQueOperationWithBank(list, bankid, name,
					null, null, type, 0, page, size);
			List<User> userlist = usermapper.selectAll();
			List<SysOrganization> organlst = organmapper.selectAll();
			Map<Integer, String> map = new HashMap<>();
			Map<String, String> map2 = new HashMap<>();
			for (SysOrganization sysOrganization : organlst) {
				if (sysOrganization.getLevel() == 1 && StringUtil.isNotEmpty(sysOrganization.getUniqueCode())
						&& sysOrganization.getPid() == null) {
					map2.put(sysOrganization.getUniqueCode(), sysOrganization.getName());
				}
			}
			for (User user2 : userlist) {
				map.put(user2.getId(), user2.getRealname());
			}
			for (QueOperationWithBank queOperationWithBank : operationlist) {
				queOperationWithBank.setFree3(map.get(queOperationWithBank.getCreaterId()));
				queOperationWithBank.setFree5(map2.get(queOperationWithBank.getOrganCode()));
			}

			Map<String, Object> result = new HashMap<>();
			result.put("total", operationmapper
					.selectQueOperationWithBank(list, bankid, name, null, null, type, 0, null, null).size());
			result.put("pageNum", page);
			result.put("pageSize", size);
			result.put("list", operationlist);

			return result;
		} else {
			return null;
		}
	}

	@Override
	public Map<String, Object> getFreeOperation(String tag, String bankid, String name, Integer type, Integer userid,
			Integer page, Integer size) {
		// TODO Auto-generated method stub
		/*
		 * User user = usermapper.selectByPrimaryKey(userid); SysOrganization organ =
		 * organmapper.selectByPrimaryKey(user.getOrganId()); String organcode =
		 * organ.getUniqueCode(); if(StringUtil.isNotEmpty(organcode)) { //
		 * 首先查看organcode是否有效 Example example = new Example(SysOrganization.class);
		 * Example.Criteria criteria = example.createCriteria();
		 * criteria.andEqualTo("uniqueCode", organcode); List<SysOrganization> result =
		 * organmapper.selectByExample(example); if (result == null || result.size() ==
		 * 0) { // 没有对应的组织 return null; } // 如果有的话，查看id是否对应 if
		 * (!user.getOrganId().equals(result.get(0).getId())) { // 用户的组织和传来的组织对不上 return
		 * null; } }
		 */
		/**
		 * 以下是正常情况
		 */
		List<String> list = new ArrayList<String>();
		if (StringUtil.isNotEmpty(tag)) {
			String[] tags = tag.split(",");
			for (String string : tags) {
				list.add(string);
			}
		}
		List<QueOperationWithBank> operationlist = operationmapper.selectQueOperationWithBank(list, bankid, name, null,
				null, type, 1, page, size);
		List<User> userlist = usermapper.selectAll();
		List<SysOrganization> organlst = organmapper.selectAll();
		Map<Integer, String> map = new HashMap<>();
		Map<String, String> map2 = new HashMap<>();
		for (SysOrganization sysOrganization : organlst) {
			if (sysOrganization.getLevel() == 1 && StringUtil.isNotEmpty(sysOrganization.getUniqueCode())
					&& sysOrganization.getPid() == null) {
				map2.put(sysOrganization.getUniqueCode(), sysOrganization.getName());
			}
		}
		for (User user2 : userlist) {
			map.put(user2.getId(), user2.getRealname());
		}
		for (QueOperationWithBank queOperationWithBank : operationlist) {
			queOperationWithBank.setFree3(map.get(queOperationWithBank.getCreaterId()));
			queOperationWithBank.setFree5(map2.get(queOperationWithBank.getOrganCode()));
		}

		Map<String, Object> result = new HashMap<>();
		result.put("total",
				operationmapper.selectQueOperationWithBank(list, bankid, name, null, null, type, 1, null, null).size());
		result.put("pageNum", page);
		result.put("pageSize", size);
		result.put("list", operationlist);

		return result;

	}

	@Override
	public int syncQuesbank(String json) {
		// json =
		// "{\"id\":\"a7036bb148384d2bb93a0dc122654ab1\",\"no\":0,\"title\":\"Office一级test\",\"time\":0,\"sumScore\":0,\"remarks\":null,\"type\":0,\"version\":1,\"createTime\":\"1545593390853\",\"createrId\":null,\"updateTime\":\"0\",\"updateId\":null,\"difficultyId\":0,\"tagName\":null,\"packageUrl\":\"a7036bb148384d2bb93a0dc122654ab1\",\"organCode\":null,\"status\":0,\"free1\":null,\"free2\":null,\"free3\":null,\"free4\":0,\"free5\":null,\"choice\":[{\"id\":\"a23eb76279f44a3c92740c15f6f2959e\",\"no\":1,\"title\":\"选择1\\r\\n\",\"rightAnswer\":\"\",\"type\":\"1\",\"score\":1,\"section\":null,\"analysis\":\"\",\"bankId\":\"a7036bb148384d2bb93a0dc122654ab1\",\"createTime\":\"0\",\"tagName\":null,\"createrId\":null,\"updateTime\":\"0\",\"updateId\":null,\"free4\":0,\"item\":[{\"id\":\"d7fd183db22245cf8c5fe390c7459b7c\",\"itemNo\":\"0\",\"itemabcd\":\"A\",\"choiceId\":\"a23eb76279f44a3c92740c15f6f2959e\",\"itemContent\":\"aaaaaaaaaaaaaaaaa\\r\\n\",\"createTime\":\"0\",\"createrId\":null,\"updateTime\":\"0\",\"updateId\":null},{\"id\":\"385f5d7bb4eb46f4ae9ec621dbdc8ee2\",\"itemNo\":\"1\",\"itemabcd\":\"B\",\"choiceId\":\"a23eb76279f44a3c92740c15f6f2959e\",\"itemContent\":\"bbbbbbbbbbbbbbbbbbb\\r\\n\",\"createTime\":\"0\",\"createrId\":null,\"updateTime\":\"0\",\"updateId\":null},{\"id\":\"a59af00fa4ca4777a28239037fa224a0\",\"itemNo\":\"2\",\"itemabcd\":\"C\",\"choiceId\":\"a23eb76279f44a3c92740c15f6f2959e\",\"itemContent\":\"ccccccccccccccccccccc\\r\\n\",\"createTime\":\"0\",\"createrId\":null,\"updateTime\":\"0\",\"updateId\":null},{\"id\":\"f3656a06c2d649b2a44141856369284e\",\"itemNo\":\"3\",\"itemabcd\":\"D\",\"choiceId\":\"a23eb76279f44a3c92740c15f6f2959e\",\"itemContent\":\"dddddddddddddddddd\\r\\n\",\"createTime\":\"0\",\"createrId\":null,\"updateTime\":\"0\",\"updateId\":null}]},{\"id\":\"119ed513612848c5aadf5d4bf5ef20b1\",\"no\":2,\"title\":\"选择2\\r\\n\",\"rightAnswer\":\"\",\"type\":\"1\",\"score\":1,\"section\":null,\"analysis\":\"\",\"bankId\":\"a7036bb148384d2bb93a0dc122654ab1\",\"createTime\":\"0\",\"tagName\":null,\"createrId\":null,\"updateTime\":\"0\",\"updateId\":null,\"free4\":0,\"item\":[{\"id\":\"7ab5ac500eb5429881274f40395de447\",\"itemNo\":\"0\",\"itemabcd\":\"A\",\"choiceId\":\"119ed513612848c5aadf5d4bf5ef20b1\",\"itemContent\":\"aaaaaaaaaaaaaaaaaaaa\\r\\n\",\"createTime\":\"0\",\"createrId\":null,\"updateTime\":\"0\",\"updateId\":null},{\"id\":\"7d1ac6aaab1341c2a4cfc0188bc520bb\",\"itemNo\":\"1\",\"itemabcd\":\"B\",\"choiceId\":\"119ed513612848c5aadf5d4bf5ef20b1\",\"itemContent\":\"bbbbbbbbbbbbbbbb\\r\\n\",\"createTime\":\"0\",\"createrId\":null,\"updateTime\":\"0\",\"updateId\":null},{\"id\":\"87be601b8a3643d49be14561ec7f4b19\",\"itemNo\":\"2\",\"itemabcd\":\"C\",\"choiceId\":\"119ed513612848c5aadf5d4bf5ef20b1\",\"itemContent\":\"ccccccccccccccccccccc\\r\\n\",\"createTime\":\"0\",\"createrId\":null,\"updateTime\":\"0\",\"updateId\":null},{\"id\":\"456ede5815994f588194142a00d9bf75\",\"itemNo\":\"3\",\"itemabcd\":\"D\",\"choiceId\":\"119ed513612848c5aadf5d4bf5ef20b1\",\"itemContent\":\"dddddddddddddddddddd\\r\\n\",\"createTime\":\"0\",\"createrId\":null,\"updateTime\":\"0\",\"updateId\":null}]}],\"operation\":[{\"no\":\"1\",\"content\":\"excel\\r\\n1.打开考生文件夹，excel.xlsx文件\\r\\n2.更改sheet1名称为test\\r\\n3.保存\\r\\n\",\"id\":\"49c85926609940d0afd216913f957657\",\"analysis\":\"解析\\r\\n\",\"bankId\":\"a7036bb148384d2bb93a0dc122654ab1\",\"type\":\"2\",\"isDelete\":0,\"createTime\":\"0\",\"createrId\":null,\"updateTime\":\"0\",\"updateId\":null,\"tagName\":null,\"item\":[{\"id\":\"9b105bdc4eb94ca48bca6336c71d4940\",\"itemNo\":\"1\",\"itemTitle\":\"获取sheet名称\",\"itemScore\":1,\"itemSection\":\"\",\"operationId\":\"3baad91a28be4e40956f9406a23634cc\",\"itemType\":0,\"itemClass\":null,\"rightAnswer\":null,\"mark\":null,\"judgeway\":null,\"param\":\"\\u003cparam
		// type=\\\"string\\\" id=\\\"{0}\\\"
		// value=\\\"1\\\"\\u003e素材作者\\u003c/param\\u003e\",\"createTime\":\"0\",\"createrId\":null,\"updateTime\":\"0\",\"updateId\":null}]},{\"no\":\"1\",\"content\":\"word\\r\\n\\r\\n1.打开考生文件夹,在word.docx文件上修改hello为红色\\r\\n2保存并关闭\\r\\n\",\"id\":\"437cbab4cd32449a9052079bcc493208\",\"analysis\":\"解析\\r\\n\",\"bankId\":\"a7036bb148384d2bb93a0dc122654ab1\",\"type\":\"1\",\"isDelete\":0,\"createTime\":\"0\",\"createrId\":null,\"updateTime\":\"0\",\"updateId\":null,\"tagName\":null,\"item\":[{\"id\":\"0e8d4452eea1417d9f9a77c91cb508ec\",\"itemNo\":\"1\",\"itemTitle\":\"颜色\",\"itemScore\":1,\"itemSection\":\"\",\"operationId\":\"3024846e0e2644c8884d96a8058e1858\",\"itemType\":0,\"itemClass\":null,\"rightAnswer\":null,\"mark\":null,\"judgeway\":null,\"param\":\"\\u003cparam
		// type=\\\"string\\\" id=\\\"{0}\\\"
		// value=\\\"Hello\\\"\\u003e素材作者\\u003c/param\\u003e\",\"createTime\":\"0\",\"createrId\":null,\"updateTime\":\"0\",\"updateId\":null}]},{\"no\":\"1\",\"content\":\"ppt\\r\\n1.打开考生文件夹选中ppt.pptx\\r\\n2.更改幻灯片数量\\r\\n3.保存1\\r\\n\",\"id\":\"87467ee406c7442e9d733950900ef789\",\"analysis\":\"e1xydGYxXGFuc2lcYW5zaWNwZzEyNTJcdWMxXGh0bWF1dHNwXGRlZmYye1xmb250dGJse1xmMFxmY2hhcnNldDAgVGltZXMgTmV3IFJvbWFuO317XGYyXGZjaGFyc2V0MCBNaWNyb3NvZnQgWWFIZWkgVUk7fX17XGNvbG9ydGJsXHJlZDBcZ3JlZW4wXGJsdWUwO1xyZWQyNTVcZ3JlZW4yNTVcYmx1ZTI1NTt9XGxvY2hcaGljaFxkYmNoXHBhcmRccGxhaW5cbHRycGFyXGl0YXAwe1xsYW5nMTAzM1xmczI0XGYyXGNmMCBcY2YwXHFse1xmMiB7XGxhbmcyMDUyXGx0cmNoIFx1LTMwMjM3P1x1MjY1MTI/fVxsaTBccmkwXHNhMFxzYjBcZmkwXHFsXHBhcn0NCn0NCn0=\",\"bankId\":\"a7036bb148384d2bb93a0dc122654ab1\",\"type\":\"3\",\"isDelete\":0,\"createTime\":\"0\",\"createrId\":null,\"updateTime\":\"0\",\"updateId\":null,\"tagName\":null,\"item\":[{\"id\":\"2bc4dd3708c4402f93571077f4794c32\",\"itemNo\":\"1\",\"itemTitle\":\"幻灯片数量\",\"itemScore\":1,\"itemSection\":\"\",\"operationId\":\"ef7895d9e4314bf09c35f7eb301377b4\",\"itemType\":0,\"itemClass\":null,\"rightAnswer\":null,\"mark\":null,\"judgeway\":null,\"param\":\"\",\"createTime\":\"0\",\"createrId\":null,\"updateTime\":\"0\",\"updateId\":null}]},{\"no\":\"1\",\"content\":null,\"id\":\"a0716ed803634800bd7d585e86e5c3cd\",\"analysis\":null,\"bankId\":\"a7036bb148384d2bb93a0dc122654ab1\",\"type\":\"4\",\"isDelete\":0,\"createTime\":\"0\",\"createrId\":null,\"updateTime\":\"0\",\"updateId\":null,\"tagName\":null,\"item\":[{\"id\":null,\"itemNo\":\"1\",\"itemTitle\":\"文件新建\",\"itemScore\":1,\"itemSection\":\"\",\"operationId\":\"6e8adf4d275148e08aea9b773bb5026f\",\"itemType\":0,\"itemClass\":\"NewFile\",\"rightAnswer\":null,\"mark\":null,\"judgeway\":null,\"param\":\"\\u003cparam
		// id=\\\"1\\\" name=\\\"path\\\"
		// value=\\\"a\\\\1.txt\\\"\\u003e路径\\u003c/param\\u003e\",\"createTime\":\"0\",\"createrId\":null,\"updateTime\":\"0\",\"updateId\":null}]},{\"no\":\"1\",\"content\":\"打开ie输入
		// http:localhost:1234/index.html，下载1.jpg到考生文件夹\\r\\n\",\"id\":\"286f82a859034b7a921de394c8da38fc\",\"analysis\":\"\",\"bankId\":\"a7036bb148384d2bb93a0dc122654ab1\",\"type\":\"5\",\"isDelete\":0,\"createTime\":\"0\",\"createrId\":null,\"updateTime\":\"0\",\"updateId\":null,\"tagName\":null,\"item\":[{\"id\":\"ac3ae74fb0b4476ba417bdf82535b9fa\",\"itemNo\":\"1\",\"itemTitle\":\"文件下载\",\"itemScore\":1,\"itemSection\":\"\",\"operationId\":\"0ccd5d87a12e4114b4cd9e4c28054c0b\",\"itemType\":0,\"itemClass\":\"IE.DownLoadFile\",\"rightAnswer\":null,\"mark\":null,\"judgeway\":null,\"param\":\"\\u003cparam
		// id=\\\"1\\\" name=\\\"path\\\"
		// value=\\\"1.jpg\\\"\\u003e保存路径\\u003c/param\\u003e\",\"createTime\":\"0\",\"createrId\":null,\"updateTime\":\"0\",\"updateId\":null}]},{\"no\":\"1\",\"content\":\"1.接收并阅读邮件\\r\\n2.回复主题Happy
		// 内容Hello\\r\\n\",\"id\":\"635873f61c6d4595a4d358a57098c10f\",\"analysis\":\"\",\"bankId\":\"a7036bb148384d2bb93a0dc122654ab1\",\"type\":\"5\",\"isDelete\":0,\"createTime\":\"0\",\"createrId\":null,\"updateTime\":\"0\",\"updateId\":null,\"tagName\":null,\"item\":[{\"id\":\"32ab92c5d5f34c34bcba98d5b4419d08\",\"itemNo\":\"1\",\"itemTitle\":\"接收邮件\",\"itemScore\":1,\"itemSection\":\"\",\"operationId\":\"7822ca7ecbdf4891a89a8f79a84e630d\",\"itemType\":0,\"itemClass\":\"Mail.Receive\",\"rightAnswer\":null,\"mark\":null,\"judgeway\":null,\"param\":\"\\u003cparam
		// id=\\\"1\\\" name=\\\"sender\\\" value=\\\"lihua\\\"
		// type=\\\"string\\\"\\u003e发件人\\u003c/param\\u003e\\u003cparam id=\\\"2\\\"
		// name=\\\"subject\\\" value=\\\"Happy NeaYear\\\"
		// type=\\\"string\\\"\\u003e主题\\u003c/param\\u003e\\u003cparam id=\\\"2\\\"
		// name=\\\"content\\\" value=\\\"Hello\\\"
		// type=\\\"string\\\"\\u003e内容\\u003c/param\\u003e\",\"createTime\":\"0\",\"createrId\":null,\"updateTime\":\"0\",\"updateId\":null},{\"id\":\"eb5e066816224a2092122112e7cd1604\",\"itemNo\":\"2\",\"itemTitle\":\"回复邮件\",\"itemScore\":1,\"itemSection\":\"\",\"operationId\":\"616b4792863f4035aa72184975ec29d2\",\"itemType\":0,\"itemClass\":\"Mail.Reply\",\"rightAnswer\":null,\"mark\":null,\"judgeway\":null,\"param\":\"\\u003cparam
		// id=\\\"4\\\" name=\\\"subject\\\" value=\\\"Happy\\\"
		// type=\\\"string\\\"\\u003e主题\\u003c/param\\u003e\\u003cparam id=\\\"5\\\"
		// name=\\\"content\\\" value=\\\"Hello\\\"
		// type=\\\"string\\\"\\u003e内容\\u003c/param\\u003e\\u003cparam id=\\\"5\\\"
		// name=\\\"makeCopy\\\" value=\\\"\\\"
		// type=\\\"string\\\"\\u003e抄送（多个时逗号或顿号分隔）\\u003c/param\\u003e\",\"createTime\":\"0\",\"createrId\":null,\"updateTime\":\"0\",\"updateId\":null}]}],\"choiceQuestion\":null}";
		GsonBuilder builder = new GsonBuilder();
		builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {

			@Override
			public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
					throws JsonParseException {
				// TODO Auto-generated method stub
				return new Date(json.getAsJsonPrimitive().getAsLong());
			}
		});
		try {
			QuestionBank bank = builder.create().fromJson(json, QuestionBank.class);
			List<QueChoice> choice = bank.getChoice();
			List<QueOperation> operation = bank.getOperation();
			if (StringUtil.isEmpty(bank.getOrganCode())) {
				// 组织code没传
				return -3;
			}
			/**
			 * 首先保存考试信息
			 */
			bank.setIsDelete(0);
			// 查看考卷信息是否已经存在
			QuestionBank qb = questionBankMapper.selectByPrimaryKey(bank.getId());
			if (qb == null) {
				int ok = questionBankMapper.insertSelective(bank);
				if (ok != 1) {
					// 保存试卷信息失败
					return -2;
				}
			} else {
				// 已存在，报错
				return -4;
			}
			/**
			 * 循环客观题，进行保存
			 */
			try {
				for (QueChoice queChoice : choice) {
					if (queChoice.getType().equals("3")) {
						// 填空
						/**
						 * 填空题，不管子集
						 */
						queChoice.setOrganCode(bank.getOrganCode());
						List<QueChoiceitem> ilist = queChoice.getItem();
						/**
						 * 查看该题是否存在
						 */
						if (choicemapper.selectByPrimaryKey(queChoice.getId()) == null) {
							String analysistext = queChoice.getAnalysis();
							// 不存在，保存关联
							QueChoiceBank temp = new QueChoiceBank();
							temp.setId(Tool.getUUID());
							temp.setBankId(bank.getId());
							temp.setChoiceId(queChoice.getId());
							temp.setChoiceNo(queChoice.getNo());
							temp.setCreater(queChoice.getCreaterId());
							temp.setCreateTime(new Date());
							choicebankmapper.insertSelective(temp);
							// 保存子集
							for (QueChoiceitem queChoiceitem : ilist) {
								try {
									choiceitemmapper.insertSelective(queChoiceitem);
								} catch (Exception e) {
									e.printStackTrace();
									continue;
								}
							}
							// 不存在，保存题目
							queChoice.setIsDelete(0);
							queChoice.setStatus(0);
							queChoice.setAnalysis(null);
							choicemapper.insertSelective(queChoice);
							// 保存题目解析
							QueChoiceAnalysis analysis = new QueChoiceAnalysis();
							analysis.setId(queChoice.getId());
							analysis.setAnalysis(analysistext);
							analysis.setBankId(bank.getId());
							quechoiceAnalysisMapper.insertSelective(analysis);
						} else {
							// 题库存在，只需要保存关联表
							/**
							 * 验证是否关联表数据已经存在
							 */
							Example example = new Example(QueChoiceBank.class);
							Example.Criteria criteria = example.createCriteria();
							criteria.andEqualTo("bankId", bank.getId());
							criteria.andEqualTo("choiceId", queChoice.getId());
							if (choicebankmapper.selectByExample(example).size() <= 0) {
								// 不存在旧的关联数据，保存
								QueChoiceBank temp = new QueChoiceBank();
								temp.setId(Tool.getUUID());
								temp.setBankId(bank.getId());
								temp.setChoiceId(queChoice.getId());
								temp.setChoiceNo(queChoice.getNo());
								temp.setCreater(queChoice.getCreaterId());
								temp.setCreateTime(new Date());
								choicebankmapper.insertSelective(temp);
							}

						}
					} else if (queChoice.getType().equals("2")) {
						// 判断
						/**
						 * 判断题，不管子集
						 */
						queChoice.setOrganCode(bank.getOrganCode());
						/**
						 * 查看该题是否存在
						 */
						if (choicemapper.selectByPrimaryKey(queChoice.getId()) == null) {
							String analysistext = queChoice.getAnalysis();
							// 不存在，保存关联
							QueChoiceBank temp = new QueChoiceBank();
							temp.setId(Tool.getUUID());
							temp.setBankId(bank.getId());
							temp.setChoiceId(queChoice.getId());
							temp.setChoiceNo(queChoice.getNo());
							temp.setCreater(queChoice.getCreaterId());
							temp.setCreateTime(new Date());
							choicebankmapper.insertSelective(temp);
							// 不存在，保存题目
							queChoice.setIsDelete(0);
							queChoice.setStatus(0);
							queChoice.setAnalysis(null);
							choicemapper.insertSelective(queChoice);
							// 保存题目解析
							QueChoiceAnalysis analysis = new QueChoiceAnalysis();
							analysis.setId(queChoice.getId());
							analysis.setAnalysis(analysistext);
							analysis.setBankId(bank.getId());
							quechoiceAnalysisMapper.insertSelective(analysis);
						} else {
							// 题库存在，只需要保存关联表
							/**
							 * 验证是否关联表数据已经存在
							 */
							Example example = new Example(QueChoiceBank.class);
							Example.Criteria criteria = example.createCriteria();
							criteria.andEqualTo("bankId", bank.getId());
							criteria.andEqualTo("choiceId", queChoice.getId());
							if (choicebankmapper.selectByExample(example).size() <= 0) {
								// 不存在旧的关联数据，保存
								QueChoiceBank temp = new QueChoiceBank();
								temp.setId(Tool.getUUID());
								temp.setBankId(bank.getId());
								temp.setChoiceId(queChoice.getId());
								temp.setChoiceNo(queChoice.getNo());
								temp.setCreater(queChoice.getCreaterId());
								temp.setCreateTime(new Date());
								choicebankmapper.insertSelective(temp);
							}

						}

					} else if (queChoice.getType().equals("1")) {
						// 选择
						/**
						 * 选择题，需要判断子集，保存
						 */
						queChoice.setOrganCode(bank.getOrganCode());
						List<QueChoiceitem> itemlist = queChoice.getItem();
						/**
						 * 查看该题是否存在
						 */
						if (choicemapper.selectByPrimaryKey(queChoice.getId()) == null) {
							String analysistext = queChoice.getAnalysis();
							// 保存关联
							QueChoiceBank temp = new QueChoiceBank();
							temp.setId(Tool.getUUID());
							temp.setBankId(bank.getId());
							temp.setChoiceId(queChoice.getId());
							temp.setChoiceNo(queChoice.getNo());
							temp.setCreater(queChoice.getCreaterId());
							temp.setCreateTime(new Date());
							choicebankmapper.insertSelective(temp);
							// 保存子集
							for (QueChoiceitem queChoiceitem : itemlist) {
								choiceitemmapper.insertSelective(queChoiceitem);
							}
							// 不存在，保存题目
							queChoice.setIsDelete(0);
							queChoice.setStatus(0);
							queChoice.setAnalysis(null);
							choicemapper.insertSelective(queChoice);
							// 保存题目解析
							QueChoiceAnalysis analysis = new QueChoiceAnalysis();
							analysis.setId(queChoice.getId());
							analysis.setAnalysis(analysistext);
							analysis.setBankId(bank.getId());
							quechoiceAnalysisMapper.insertSelective(analysis);
							

						} else {
							// 题库存在，只需要保存关联表
							/**
							 * 验证是否关联表数据已经存在
							 */
							Example example = new Example(QueChoiceBank.class);
							Example.Criteria criteria = example.createCriteria();
							criteria.andEqualTo("bankId", bank.getId());
							criteria.andEqualTo("choiceId", queChoice.getId());
							if (choicebankmapper.selectByExample(example).size() <= 0) {
								QueChoiceBank temp = new QueChoiceBank();
								temp.setId(Tool.getUUID());
								temp.setBankId(bank.getId());
								temp.setChoiceId(queChoice.getId());
								temp.setChoiceNo(queChoice.getNo());
								temp.setCreater(queChoice.getCreaterId());
								temp.setCreateTime(new Date());
								choicebankmapper.insertSelective(temp);
							}
						}
					}
				}
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
				// 删除试卷客观题第三方关联
				Example example = new Example(QueChoiceBank.class);
				Example.Criteria criteria = example.createCriteria();
				criteria.andEqualTo("bankId", bank.getId());
				choicebankmapper.deleteByExample(example);
				// 删除试卷对应的客观题
				Example ex = new Example(QueChoice.class);
				Example.Criteria c = ex.createCriteria();
				c.andEqualTo("bankId", bank.getId());
				choicemapper.deleteByExample(ex);
				// 删除解析表的数据
				Example exa = new Example(QueChoiceAnalysis.class);
				Example.Criteria cr = exa.createCriteria();
				cr.andEqualTo("bankId", bank.getId());
				quechoiceAnalysisMapper.deleteByExample(exa);
				// 删除试卷主信息
				questionBankMapper.deleteByPrimaryKey(bank.getId());
				// 保存客观题失败
				return -5;
			}

			/**
			 * 循环主观题，进行保存
			 */
			try {
				for (QueOperation queOperation : operation) {
					// 主观题
					/**
					 * 选择题，需要判断子集，保存
					 */
					queOperation.setOrganCode(bank.getOrganCode());
					List<QueOperationItem> itemlist = queOperation.getItem();
					/**
					 * 查看该题是否存在
					 */
					if (operationmapper.selectByPrimaryKey(queOperation.getId()) == null) {
						String analysistext = queOperation.getAnalysis();
						// 保存关联
						QueOperationBank temp = new QueOperationBank();
						temp.setId(Tool.getUUID());
						temp.setBankId(bank.getId());
						temp.setOperationId(queOperation.getId());
						temp.setOperationNo(queOperation.getNo());
						temp.setCreater(queOperation.getCreaterId());
						temp.setCreateTime(new Date());
						operationbankmapper.insertSelective(temp);

						// 保存子集
						for (QueOperationItem queOperationItem : itemlist) {
							try {
								operationitemmapper.insertSelective(queOperationItem);
							} catch (Exception e) {
								e.printStackTrace();
								continue;
							}

						}
						// 不存在，保存题目
						queOperation.setIsDelete(0);
						queOperation.setStatus(0);
						queOperation.setAnalysis(null);
						operationmapper.insertSelective(queOperation);
						
						// 保存题目解析
						QueOperationAnalysis analysis = new QueOperationAnalysis();
						analysis.setId(queOperation.getId());
						analysis.setAnalysis(analysistext);
						analysis.setBankId(bank.getId());
						queOperationAnalysisMapper.insertSelective(analysis);

					} else {
						// 题库存在，只需要保存关联表
						/**
						 * 验证是否关联表数据已经存在
						 */
						Example example = new Example(QueOperationBank.class);
						Example.Criteria criteria = example.createCriteria();
						criteria.andEqualTo("bankId", bank.getId());
						criteria.andEqualTo("operationId", queOperation.getId());
						if (operationbankmapper.selectByExample(example).size() <= 0) {
							QueOperationBank temp = new QueOperationBank();
							temp.setId(Tool.getUUID());
							temp.setBankId(bank.getId());
							temp.setOperationId(queOperation.getId());
							temp.setOperationNo(queOperation.getNo());
							temp.setCreater(queOperation.getCreaterId());
							temp.setCreateTime(new Date());
							operationbankmapper.insertSelective(temp);
						}
					}
				}
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
				// 删除试卷客观题第三方关联
				Example example = new Example(QueChoiceBank.class);
				Example.Criteria criteria = example.createCriteria();
				criteria.andEqualTo("bankId", bank.getId());
				choicebankmapper.deleteByExample(example);

				// 删除试卷对应的客观题
				Example ex = new Example(QueChoice.class);
				Example.Criteria c = ex.createCriteria();
				c.andEqualTo("bankId", bank.getId());
				choicemapper.deleteByExample(ex);

				// 删除试卷客观题第三方关联
				Example example2 = new Example(QueOperationBank.class);
				Example.Criteria criteria2 = example2.createCriteria();
				criteria2.andEqualTo("bankId", bank.getId());
				operationbankmapper.deleteByExample(example2);

				// 删除试卷对应的主观题
				Example ex2 = new Example(QueOperation.class);
				Example.Criteria c2 = ex2.createCriteria();
				c2.andEqualTo("bankId", bank.getId());
				operationmapper.deleteByExample(ex2);
				
				// 删除试卷的解析
				Example exa = new Example(QueChoiceAnalysis.class);
				Example.Criteria cr = exa.createCriteria();
				cr.andEqualTo("bankId", bank.getId());
				quechoiceAnalysisMapper.deleteByExample(exa);
				
				// 删除解析表的数据
				Example exa2 = new Example(QueOperationAnalysis.class);
				Example.Criteria cr2 = exa2.createCriteria();
				cr2.andEqualTo("bankId", bank.getId());
				queOperationAnalysisMapper.deleteByExample(exa2);

				// 删除试卷主信息
				questionBankMapper.deleteByPrimaryKey(bank.getId());
				// 保存主观题失败
				return -6;
			}

		} catch (Exception e) {
			// TODO: handle exception
			// 数据无法解析
			return -1;
		}
		return 1;
	}

	@Override
	public List<QuestionBank> selectByParams(QuestionBank bank) {

		Example example = new Example(QuestionBank.class);
		Criteria cO = example.createCriteria();
		Criteria cP = example.createCriteria();

		if (bank.getCreaterId() != null) {
			cO.andEqualTo("createrId", bank.getCreaterId()).andEqualTo("status", 0).andEqualTo("isDelete", 0);

			if (bank.getDifficultyId() != null) {
				cO.andEqualTo("difficultyId", bank.getDifficultyId());
			}

			cP.andEqualTo("status", 1).andEqualTo("isDelete", 0);

			if (bank.getDifficultyId() != null) {
				cP.andEqualTo("difficultyId", bank.getDifficultyId());
			}

			example.or(cP);
		} else if (bank.getOrganCode() != null && !"".equals(bank.getOrganCode())) {
			cO.andEqualTo("organCode", bank.getOrganCode()).andEqualTo("status", 0).andEqualTo("isDelete", 0);

			if (bank.getDifficultyId() != null) {
				cO.andEqualTo("difficultyId", bank.getDifficultyId());
			}

			cP.andEqualTo("status", 1).andEqualTo("isDelete", 0);

			if (bank.getDifficultyId() != null) {
				cP.andEqualTo("difficultyId", bank.getDifficultyId());
			}

			example.or(cP);
		} else {
			if (bank.getDifficultyId() != null) {
				cO.andEqualTo("difficultyId", bank.getDifficultyId());
			}

			cO.andEqualTo("status", 1).andEqualTo("isDelete", 0);
		}

		example.setOrderByClause(" create_time desc ");
		
		List<QuestionBank> banks = questionBankMapper.selectByExample(example);

		for (QuestionBank item : banks) {
			if (item.getStatus() == 0) {
				item.setTitle(item.getTitle() + "（私有题库）");
			} else if (item.getStatus() == 1) {
				item.setTitle(item.getTitle() + "（公共题库）");
			}
		}
		
		return banks;
	}

	@Override
	public PageInfo<QueChoice> getChoiceByBank(QueChoice choice, Integer page, Integer size) {
		List<User> userlist = usermapper.selectAll();
		List<SysOrganization> organlst = organmapper.selectAll();
		Map<Integer, String> map = new HashMap<>();
		Map<String, String> map2 = new HashMap<>();
		for (SysOrganization sysOrganization : organlst) {
			if (sysOrganization.getLevel() == 1 && StringUtil.isNotEmpty(sysOrganization.getUniqueCode())
					&& sysOrganization.getPid() == null) {
				map2.put(sysOrganization.getUniqueCode(), sysOrganization.getName());
			}
		}
		for (User user2 : userlist) {
			map.put(user2.getId(), user2.getRealname());
		}
		// TODO Auto-generated method stub
		Example ex = new Example(QueChoiceBank.class);
		Example.Criteria c = ex.createCriteria();
		c.andEqualTo("bankId", choice.getBankId());
		List<QueChoiceBank> temp = choicebankmapper.selectByExample(ex);
		List<String> ids = new ArrayList<>();
		for (QueChoiceBank queChoiceBank : temp) {
			ids.add(queChoiceBank.getChoiceId());
		}
		PageHelper.startPage(page, size);
		Example example = new Example(QueChoice.class);
		Example.Criteria criteria = example.createCriteria();
		if (StringUtil.isNotEmpty(choice.getType())) {
			criteria.andEqualTo("type", choice.getType());
		}
		if (StringUtil.isNotEmpty(choice.getTitle())) {
			criteria.andLike("title", "%" + choice.getTitle() + "%");
		}

		if (StringUtil.isNotEmpty(choice.getTagName())) {
			String tagName = choice.getTagName();
			String[] tag = tagName.split(",");
			for (int i = 0; i < tag.length; i++) {
				criteria.andLike("tagName", "%" + tag[i] + "%");
			}
		}
		if(ids.size() > 0) {
			criteria.andIn("id", ids);
		}else {
			return new PageInfo<QueChoice>(new ArrayList<>());
		}
		// criteria.andEqualTo("isDelete", 0);
		example.setOrderByClause(" no asc");
		List<QueChoice> list = choicemapper.selectByExample(example);
		for (QueChoice queChoice : list) {
			queChoice.setFree3(map.get(queChoice.getCreaterId()));
			queChoice.setFree5(map2.get(queChoice.getOrganCode()));
		}
		return new PageInfo<QueChoice>(list);
	}

	@Override
	public List<QueChoiceitem> getItemByChoiceid(String Choiceid) {
		Example example = new Example(QueChoiceitem.class);
		Example.Criteria criteria = example.createCriteria();
		criteria.andEqualTo("choiceId", Choiceid);
		example.setOrderByClause(" item_no asc");
		return choiceitemmapper.selectByExample(example);
	}

	@Override
	public PageInfo<QueOperation> getOperationByBank(QueOperation operation, Integer page, Integer size) {
		List<User> userlist = usermapper.selectAll();
		List<SysOrganization> organlst = organmapper.selectAll();
		Map<Integer, String> map = new HashMap<>();
		Map<String, String> map2 = new HashMap<>();
		for (SysOrganization sysOrganization : organlst) {
			if (sysOrganization.getLevel() == 1 && StringUtil.isNotEmpty(sysOrganization.getUniqueCode())
					&& sysOrganization.getPid() == null) {
				map2.put(sysOrganization.getUniqueCode(), sysOrganization.getName());
			}
		}
		for (User user2 : userlist) {
			map.put(user2.getId(), user2.getRealname());
		}
		// TODO Auto-generated method stub
		Example ex = new Example(QueOperationBank.class);
		Example.Criteria c = ex.createCriteria();
		c.andEqualTo("bankId", operation.getBankId());
		List<QueOperationBank> temp = operationbankmapper.selectByExample(ex);
		List<String> ids = new ArrayList<>();
		for (QueOperationBank queOperationBank : temp) {
			ids.add(queOperationBank.getOperationId());
		}
		PageHelper.startPage(page, size);
		Example example = new Example(QueOperation.class);
		Example.Criteria criteria = example.createCriteria();
		if (operation.getType() != null) {
			criteria.andEqualTo("type", operation.getType());
		}
		if (StringUtil.isNotEmpty(operation.getContent())) {
			criteria.andLike("content", "%" + operation.getContent() + "%");
		}
		if (StringUtil.isNotEmpty(operation.getTagName())) {
			String tagName = operation.getTagName();
			String[] tag = tagName.split(",");
			for (int i = 0; i < tag.length; i++) {
				criteria.andLike("tagName", "%" + tag[i] + "%");
			}
		}
		if(ids.size() > 0) {
			criteria.andIn("id", ids);
		}else {
			return new PageInfo<QueOperation>(new ArrayList<>());
		}
		// criteria.andEqualTo("isDelete", 0);
		example.setOrderByClause(" no asc");
		List<QueOperation> list = operationmapper.selectByExample(example);
		for (QueOperation queOperation : list) {
			queOperation.setFree3(map.get(queOperation.getCreaterId()));
			queOperation.setFree5(map2.get(queOperation.getOrganCode()));
		}
		return new PageInfo<QueOperation>(list);
	}

	@Override
	public int deleteChoice(Integer userid, String id) {
		// TODO Auto-generated method stub
		QueChoice choice = choicemapper.selectByPrimaryKey(id);
		if (choice == null) {
			// 找不到题目
			return -1;
		} else {
			choice.setUpdateId(userid);
			choice.setUpdateTime(new Date());
			choice.setIsDelete(1);
			return choicemapper.updateByPrimaryKeySelective(choice);
		}
	}

	@Override
	public int deleteOperation(Integer userid, String id) {
		// TODO Auto-generated method stub
		QueOperation operation = operationmapper.selectByPrimaryKey(id);
		if (operation == null) {
			// 找不到题目
			return -1;
		} else {
			operation.setUpdateId(userid);
			operation.setUpdateTime(new Date());
			operation.setIsDelete(1);
			return operationmapper.updateByPrimaryKeySelective(operation);
		}
	}

	@Override
	public int deleteBank(Integer userid, String id) {
		// TODO Auto-generated method stub
		// 首先获取卷子
		QuestionBank bank = questionBankMapper.selectByPrimaryKey(id);
		if (bank == null) {
			// 找不到试卷
			return -1;
		} else {
			bank.setUpdateId(userid);
			bank.setUpdateTime(new Date());
			bank.setIsDelete(1);
			return questionBankMapper.updateByPrimaryKeySelective(bank);
		}
	}

	@Override
	public Set<String> getAllUsefulQuestionByBank(String ids) {
		// TODO Auto-generated method stub
		String[] id = ids.split(",");
		Set<String> set = new HashSet<>();
		for (int i = 0; i < id.length; i++) {
			/**
			 * 首先获取主观操作题的题目id，条件为，关联表存在，自身没有被标记为错题
			 */
			Example ex = new Example(QueOperationBank.class);
			Example.Criteria c = ex.createCriteria();
			c.andEqualTo("bankId", id[i]);
			List<QueOperationBank> temp = operationbankmapper.selectByExample(ex);
			List<String> a = new ArrayList<>();
			for (QueOperationBank queOperationBank : temp) {
				a.add(queOperationBank.getOperationId());
			}
			if (a.size() > 0) {
				Example example = new Example(QueOperation.class);
				Example.Criteria criteria = example.createCriteria();
				criteria.andIn("id", a);
				criteria.andEqualTo("isDelete", 0);
				List<QueOperation> list = operationmapper.selectByExample(example);
				for (QueOperation queOperation : list) {
					set.add(queOperation.getId());
				}
			}
			/**
			 * 然后获取客观题的题目id，条件为，关联表存在，自身没有被标记为错题
			 */
			Example ex2 = new Example(QueChoiceBank.class);
			Example.Criteria c2 = ex2.createCriteria();
			c2.andEqualTo("bankId", id[i]);
			List<QueChoiceBank> temp2 = choicebankmapper.selectByExample(ex2);
			List<String> a2 = new ArrayList<>();
			for (QueChoiceBank queChoiceBank : temp2) {
				a2.add(queChoiceBank.getChoiceId());
			}
			Example example2 = new Example(QueChoice.class);
			Example.Criteria criteria2 = example2.createCriteria();
			if (a2.size() > 0) {
				criteria2.andIn("id", a2);
				criteria2.andEqualTo("isDelete", 0);
				List<QueChoice> list2 = choicemapper.selectByExample(example2);
				for (QueChoice queChoice : list2) {
					set.add(queChoice.getId());
				}
			}
		}
		return set;
	}

	@Override
	public int shareQuestionBank(Integer userid, String id) {
		// TODO Auto-generated method stub
		QuestionBank bank = questionBankMapper.selectByPrimaryKey(id);
		if (bank == null) {
			return -1;
		} else {
			// 分享试卷
			bank.setUpdateId(userid);
			bank.setUpdateTime(new Date());
			bank.setStatus(1);
			questionBankMapper.updateByPrimaryKeySelective(bank);
			// 分享里面的客观题
			Example ex = new Example(QueChoiceBank.class);
			Example.Criteria c = ex.createCriteria();
			c.andEqualTo("bankId", id);
			List<QueChoiceBank> list = choicebankmapper.selectByExample(ex);
			List<String> ids = new ArrayList<>();
			for (QueChoiceBank queChoiceBank : list) {
				ids.add(queChoiceBank.getChoiceId());
			}
			Example ex2 = new Example(QueChoice.class);
			Example.Criteria c2 = ex2.createCriteria();
			c2.andIn("id", ids);
			List<QueChoice> choicelist = choicemapper.selectByExample(ex2);
			for (QueChoice queChoice : choicelist) {
				queChoice.setStatus(1);
				choicemapper.updateByPrimaryKeySelective(queChoice);
			}
			// 分享里面的主观题
			Example ex3 = new Example(QueOperationBank.class);
			Example.Criteria c3 = ex3.createCriteria();
			c3.andEqualTo("bankId", id);
			List<QueOperationBank> list2 = operationbankmapper.selectByExample(ex3);
			ids = new ArrayList<>();
			for (QueOperationBank queOperationBank : list2) {
				ids.add(queOperationBank.getOperationId());
			}
			Example ex4 = new Example(QueOperation.class);
			Example.Criteria c4 = ex4.createCriteria();
			c4.andIn("id", ids);
			List<QueOperation> operationlist = operationmapper.selectByExample(ex4);
			for (QueOperation queOperation : operationlist) {
				queOperation.setStatus(1);
				operationmapper.updateByPrimaryKeySelective(queOperation);
			}
			return 1;
		}
	}

	@Override
	public int shareChoiceOrOperation(Integer type, String id, Integer userid) {
		if(StringUtil.isEmpty(id)) {
			return -3;
		}
		// TODO Auto-generated method stub
		switch (type) {
		case 1:
			// 客观题
			QueChoice choice = choicemapper.selectByPrimaryKey(id);
			if (choice == null) {
				// 找不到题目
				return -2;
			} else {
				choice.setStatus(1);
				choice.setUpdateTime(new Date());
				choice.setUpdateId(userid);
				return choicemapper.updateByPrimaryKeySelective(choice);
			}
		case 2:
			// 主观题
			QueOperation operation = operationmapper.selectByPrimaryKey(id);
			if (operation == null) {
				return -2;
			} else {
				operation.setStatus(1);
				operation.setUpdateId(userid);
				operation.setUpdateTime(new Date());
				return operationmapper.updateByPrimaryKeySelective(operation);
			}
		default:
			// 不支持的类型
			return -1;
		}
	}

	@Override
	public QueChoiceAnalysis getChoiceAnalysis(String id) {
		// TODO Auto-generated method stub
		QueChoiceAnalysis analysis = quechoiceAnalysisMapper.selectByPrimaryKey(id);
		return analysis;
	}

	@Override
	public QueOperationAnalysis getOperationAnalysis(String id) {
		// TODO Auto-generated method stub
		QueOperationAnalysis analysis = queOperationAnalysisMapper.selectByPrimaryKey(id);
		return analysis;
	}

}
